<!--
 * @Author: wjk
 * @Date: 2019-12-31 15:40:51
 * @LastEditors: wjk
 * @LastEditTime: 2019-12-31 15:51:20
 * @description: file content
 -->
<template>
  <base-page-view class-name="page-container sign-page-container" :style-text="'background-image: url('+pageBg+')'">
    <view class="header">
      <swiper class="swiper" :autoplay="true" :interval="1600" :duration="600" vertical circular>
        <swiper-item v-for="(item, index) in buy_mobiles" :key="index">
          <view class="swiper-item">恭喜{{ item }}获得奖励</view>
        </swiper-item>
      </swiper>
      <view class="sign-block">
        <view class="title-part">
          <view class="days">{{ alreadySignDays }}</view>
          <view class="link" @click="toMyRedPackets">我的奖励<image src="/static/images/common/icon_forward_active.png" mode="aspectFit" /></view>
        </view>
        <view v-if="sign_log && sign_log.length" class="content-part">
          <view v-for="(item, index) in sign_log" :key="index" class="sign-day-item" :class="{active: item.isSignIn}">
            <view class="img-container" :class="{box: item.allRewardCount > 0}">
              <template v-if="item.isSignIn">
                <b-image v-if="item.allRewardCount > 0" src="/static/images/sign-in/img_box_active.png" mode="aspectFit" :is-asset="true" />
                <b-image v-else src="/static/images/sign-in/img_gold_active.png" mode="aspectFit" :is-asset="true" />
              </template>
              <template v-else>
                <b-image v-if="item.allRewardCount > 0" src="/static/images/sign-in/img_box.png" mode="aspectFit" :is-asset="true" />
                <b-image v-else src="/static/images/sign-in/img_gold.png" mode="aspectFit" :is-asset="true" />
              </template>
            </view>
            <view class="open-text">{{ item.isSignIn ? '已签': item.name+'天' }}</view>
          </view>
        </view>
        <view class="reminder-part">
          <view class="left" @click="showRule=true"><image src="/static/images/common/icon_rule.png" mode="aspectFit" />规则</view>
          <view>签到提醒<switch :checked="is_allow_message_notice" color="#04BE02" style="transform:scale(0.7)" @change="noticeChange" /></view>
        </view>
      </view>
    </view>
    <view v-if="activityData.modules && activityData.modules.length" :style="pageStyle">
      <custom-modules :list="activityData.modules" />
    </view>

    <view class="mask" :class="{ active: (showRule||showRewards) }" @touchmove.stop="() => {}"></view>
    <view class="modal rule-modal" :class="{ active: showRule }">
      <view class="modal-content">
        <view class="title" :style="'background-image: url('+ruleTitleBg+')'">活动规则</view>
        <view class="content">
          <view v-for="(item, index) in rule_description" :key="index" class="line">{{ item }}</view>
        </view>
      </view>
      <image class="close-btn" src="/static/images/commodity/close_ico_white.png" mode="aspectFit" @click="showRule=false" />
    </view>
    <view class="modal rewards-modal" :class="{ active: showRewards }">
      <view v-if="rewardObj && rewardObj.rewards && rewardObj.rewards.length" class="modal-content">
        <view class="title">恭喜您</view>
        <view v-if="rewardObj.rule_reward_map_reward_type === 4">获得奖励{{ rewardObj.rewards.length }}选{{ rewardObj.n_num }}</view>
        <view v-else>获得{{ rewardObj.rewards.length }}份奖励</view>
        <view class="reward-list">
          <view v-for="(item, index) in rewardObj.rewards" :key="index" class="reward-item" :style="'background-image: url('+rewardItemBg+')'">
            <view class="img">
              <b-image v-if="item.pic" :src="item.pic" mode="aspectFit" />
              <b-image v-else src="/static/images/sign-in/default_gift.png" mode="aspectFit" :is-asset="true" />
            </view>
            <view class="sub-item">
              <view class="price">{{ item.price }}</view>
              <view class="title">{{ item.title }}</view>
            </view>
            <view v-if="rewardObj.rule_reward_map_reward_type === 4" class="select-btn" @click="selectReward(item)">
              <b-image v-if="item.checked" src="/static/images/sign-in/icon_select_active.png" mode="aspectFit" :is-asset="true" />
              <b-image v-else src="/static/images/sign-in/icon_select.png" mode="aspectFit" :is-asset="true" />
            </view>
            <view v-else class="btn" @click="toUseReward(item)">去使用</view>
          </view>
        </view>
        <view v-if="rewardObj.rule_reward_map_reward_type === 4" class="btn" :style="'background-image: url('+getBtnBg+')'" @click="manualGetReward">我要领取</view>
        <template v-else>
          <view class="btn" :style="'background-image: url('+getBtnBg+')'" @click="toMyRedPackets">查 看</view>
          <view class="desc">奖品已放入“我的奖励”</view>
        </template>
      </view>
    </view>
    <view class="modal sign-success-modal" :class="{ active: showSignSuccess }">
      <view class="modal-content">
        <view class="img">
          <b-image src="/static/images/sign-in/icon_gold.png" mode="aspectFit" :is-asset="true" />
        </view>
        <view>签到成功</view>
      </view>
    </view>
  </base-page-view>
</template>

<script>
import { mapState } from 'vuex'
import { getQueryString } from '@/utils/tools'
import { toFunctionDetail } from '@/utils/navigateTo'
import CustomModules from '@/components/customModules'
import './index.scss'
export default {
  components: {
    CustomModules
  },
  data() {
    return {
      page_need_login: true,
      shareOption: {},
      sign_id: 2,
      pageBg: `${process.env.VUE_APP_IMAGE_ASSET}/images/sign-in/bg_page.png`,
      buy_mobiles: [],
      sign_log: [],
      alreadySignDays: 0,
      is_allow_message_notice: false,

      showRule: false,
      ruleTitleBg: `${process.env.VUE_APP_IMAGE_ASSET}/images/sign-in/bg_rule_title.png`,
      rule_description: [],

      activityId: null,
      activityData: {
        modules: []
      },
      pageStyle: '',

      rewardObj: {
        rewards: []
      },
      rewardItemBg: `${process.env.VUE_APP_IMAGE_ASSET}/images/sign-in/bg_reward_item.png`,
      getBtnBg: `${process.env.VUE_APP_IMAGE_ASSET}/images/sign-in/bg_get_btn.png`,
      showRewards: false,
      showSignSuccess: false
    }
  },
  computed: {
    ...mapState([
      'token'
    ])
  },
  onLoad(option) {
    if (option.activity_id) {
      this.sign_id = option.activity_id
    }
  },
  onShow() {
    if (!this.token) {
      uni.setStorage({ key: 'pageAfterLogin', data: '/pagesActivity/sign-page/index' })
      this.$navigateTo('/pages/login/index', {}, 'redirectTo')
    }
  },
  onShareAppMessage(res) {
    return this.$queryShareOption(res, this.shareOption)
  },
  methods: {
    app_interactive_data(option) {
      if (option.activity_id) {
        this.sign_id = option.activity_id
      }
      this.fetchData()
    },
    async fetchData() {
      const res = await this.$api.excellentApi.getSignHome({
        activityid: this.sign_id
      })
      if (res.success && res.data) {
        const {
          name,
          buy_mobiles,
          sign_log,
          is_allow_message_notice,
          h5_link,
          rule_description,
          current_day_is_sign_in,
          share_title,
          share_description,
          share_poster,
          share_image_url
        } = res.data
        this.$setNavTitle(name || '签到')
        this.buy_mobiles = buy_mobiles || []
        this.is_allow_message_notice = !!is_allow_message_notice
        this.activityId = getQueryString('id', h5_link)
        this.getAlreadySignDays(sign_log || [])
        if (rule_description) {
          this.rule_description = rule_description.split('#')
        }
        if (this.activityId) {
          this.fetchActivityData()
        }
        if (!current_day_is_sign_in) {
          this.signPack()
        }
        this.shareOption = {
          share_title: share_title,
          share_content: share_description,
          share_icon: share_poster,
          share_cards: JSON.parse(share_image_url || '[]')
        }
        this.initShare()
      }
    },
    async fetchActivityData() {
      this.pageLoading = true
      const res = await this.$api.homeApi.getActivity({
        activity_id: this.activityId
      })
      if (res.success && res.data) {
        if (res.data.activity) {
          this.activityData = JSON.parse(res.data.activity.comment || '{ modules: [] }')
          delete res.data.activity.comment
          this.activityConfig = res.data.activity
          if (new Date(this.activityConfig.end_time * 1000) < new Date()) {
            this.activityData = {
              modules: []
            }
          } else {
            this.setBg()
          }
        }
      }
      this.pageLoading = false
    },
    // 设置背景
    setBg() {
      if (this.activityData.background) {
        this.pageStyle = `background: ${this.activityData.background}${this.activityData.background_image ? ` url(${this.activityData.background_image}) no-repeat cover` : ''};margin-top: 30rpx`
      }
    },
    getAlreadySignDays(sign_log) {
      let days = 0
      sign_log.forEach((item, index) => {
        if (item.isSignIn && item.isAllowSignIn) {
          sign_log[index]['signed'] = 1
        }
        if (item.isSignIn) {
          days += 1
        }
      })
      this.sign_log = sign_log
      this.alreadySignDays = days
    },
    // 去我的奖励
    toMyRedPackets() {
      this.showRewards = false
      this.$navigateTo('/pagesMine/my-red-packets/index')
    },
    selectReward(item) {
      if (item.checked) {
        item.checked = false
      } else {
        const selectRewards = this.rewardObj.rewards.filter(i => i.checked)
        const num = this.rewardObj.n_num - selectRewards.length
        if (num === 0) {
          uni.showToast({
            title: `最多选择${this.rewardObj.n_num}件奖品`,
            icon: 'none'
          })
        } else {
          item.checked = true
        }
      }
    },
    manualGetReward() {
      console.log(11)
      const selectRewards = this.rewardObj.rewards.filter(i => i.checked)
      if (!selectRewards.length) {
        uni.showToast({
          title: '请至少选择一件赠品',
          icon: 'none'
        })
        return
      }
      const num = this.rewardObj.n_num - selectRewards.length
      if (num > 0) {
        console.log(22)
        this.$gc.$message({
          content: `你本日还有${num}件赠品可以选择哦~ 确定只领取这些赠品吗?`,
          title: '温馨提示',
          type: 'richText',
          showMessage: true,
          showCancel: true,
          confirmText: '确定',
          cancelText: '我再看看',
          align: 'center',
          confirm: () => {
            console.log(33)
            this.toGetReward(selectRewards)
          }
        })
      } else {
        console.log(44)
        this.toGetReward(selectRewards)
      }
    },
    async toGetReward(selectRewards) {
      console.log(55)
      const res = await this.$api.excellentApi.signPartReward({
        activityid: this.sign_id,
        activitySignInLogId: this.rewardObj.activity_sign_in_log_id,
        selectRewards
      })
      console.log(66)
      if (res.success) {
        this.showRewards = false
        this.toMyRedPackets()
      }
    },
    noticeChange(e) {
      const { detail } = e
      this.is_allow_message_notice = detail.value
      if (detail.value) {
        this.setNotice(1)
      } else {
        this.$gc.$message({
          content: '关闭提醒，那漏签了怎么办',
          title: '提示',
          type: 'richText',
          showMessage: true,
          showCancel: true,
          confirmText: '继续提醒',
          cancelText: '关闭提醒',
          align: 'center',
          confirm: () => {
            this.is_allow_message_notice = true
          },
          cancel: () => {
            this.setNotice(0)
          }
        })
      }
    },
    async setNotice(val) {
      this.$sensorTrack('CLICKBUTTON', {
        button_name: 'remind',
        button_val: val
      })

      const res = await this.$api.excellentApi.signInMessageNotice({
        activity_id: this.sign_id,
        isAllowMessageNotice: val
      })
      if (res.success) {
        if (val) {
          uni.showToast({
            title: '开启后将在每日上午10:00后进行消息提醒',
            icon: 'none'
          })
        }
      } else {
        this.is_allow_message_notice = !this.is_allow_message_notice
      }
    },
    // 签到打卡
    async signPack() {
      const res = await this.$api.excellentApi.signPunch({
        activityid: this.sign_id,
        invite_code: uni.getStorageSync('share_code') || ''
      })
      if (res.success && res.data) {
        this.fetchData()
        this.rewardObj = {
          ...res.data,
          rewards: res.data.rewards.map(i => ({ ...i, checked: false }))
        }
        if (this.rewardObj.rewards.length) {
          this.$sensorTrack('WINDOWRAISE', {
            page_name: 'sign',
            page_channel: 'h5',
            window_name: 'sign_success'
          })
          this.showRewards = true
        } else {
          this.showSignSuccess = true
          setTimeout(() => {
            this.showSignSuccess = false
          }, 2000)
        }
      }
    },
    toUseReward(item) {
      let obj = {}
      if (item.reward_type === 4) {
        if (item.coupon_link_type === 'IN_PAGE' && item.coupon_state === 0) {
          obj = {
            type: item.type,
            type_val: item.goods_id,
            from_type: item.from_type,
            activity_id: item.activity_id,
            pack_type: item.pack_type
          }
          this.showRewards = false
          toFunctionDetail(obj)
        } else if (item.coupon_link_type === 'URL') {
          obj = {
            type: 0,
            type_val: item.coupon_link
          }
          this.showRewards = false
          toFunctionDetail(item)
        }
      } else if (item.get_status === 2) {
        obj = {
          type: item.type,
          type_val: item.goods_id,
          from_type: item.from_type,
          activity_id: item.activity_id,
          pack_type: item.pack_type
        }
        this.showRewards = false
        toFunctionDetail(obj)
      }
    },
    // 分享初始化
    initShare() {
      if (this.token) {
        this.shareOption.share_url = ''
        this.showShare()
      } else {
        this.hideShare()
      }
    }
  }
}
</script>
